<template>
  <view class="login page-container">
    <view class="login-header">
      欢迎使用 卡哇酒吧
    </view>

    <view class="login-main">
      <view class="login-username">
        <nut-input
          v-model="form.phoneNumber"
          autofocus
          clearable
          type="number"
          placeholder="请输入手机号"
          style="color: #fff;"
        >
          <template #left>
            <nut-icon name="../../static/images/login/IcOutlinePhoneAndroid.png" />
          </template>
        </nut-input>
      </view>

      <view v-if="usernameErrorMessage" class="login-username__error">
        <text>{{ usernameErrorMessage }}</text>
      </view>

      <view v-if="isVerificationLogin" class="login-verification">
        <nut-input
          v-model="form.verificationCode"
          clearable
          type="number"
          placeholder="请输入验证码"
          style="color: #fff;"
        >
          <template #left>
            <nut-icon name="../../static/images/login/IcOutlineLock.png" />
          </template>
        </nut-input>

        <nut-button :loading="isLoading" @click="getVerificationCode">获取验证码</nut-button>
      </view>

      <view v-else class="login-password">
        <nut-input
          v-model="form.password"
          clearable
          password
          placeholder="请输入密码"
          style="color: #fff;"
        >
          <template #left>
            <nut-icon name="../../static/images/login/IcOutlineLock.png" />
          </template>
        </nut-input>
      </view>

      <view v-if="errorMessage" class="login-password__error">
        <text>{{ errorMessage }}</text>
      </view>

      <view class="login-action">
        <nut-button class="no-border no-padding"  type="primary" plain size="small" :border="false" @click="setLoginType">{{ loginTypeSwitchText }}</nut-button>
        <nut-button class="no-border no-padding" type="primary" plain size="small" :border="false" @click="() => {uni.navigateTo({ url: '/pages/Register/index' });}">立即注册</nut-button>
      </view>

      <view class="login-btn">
        <nut-button type="primary" size="large" @click="login">登录</nut-button>
      </view>
    </view>
  </view>
  
</template>

<script setup>
import { ref } from 'vue';

import { sendVerificationCode, login as loginApi } from '../../api';
import { setToken } from '../../utils/storage';
import { USER_INFO_KEY } from '../../constants';

const form = ref({
  phoneNumber: '',
  verificationCode: '',
  password: ''
})

// #region 登录方式切换【验证码登录 / 密码登录，初始默认为验证码登录】
const isVerificationLogin = ref(true);
const loginTypeSwitchText = ref('密码登录');
const setLoginType = () => {
  isVerificationLogin.value = !isVerificationLogin.value;
  loginTypeSwitchText.value = isVerificationLogin.value ? '密码登录' : '验证码登录';
}
// #endregion

const usernameErrorMessage = ref('');
const errorMessage = ref('');
const clearErrorMessages = () => {
  usernameErrorMessage.value = '';
  errorMessage.value = '';
}

const isLoading = ref(false);
// 获取验证码
const getVerificationCode = async () => {
  isLoading.value = true;

  clearErrorMessages();

  if (form.value.phoneNumber.length !== 11) {
    usernameErrorMessage.value = '请填写正确的手机号';
    return void 0;
  }

  await sendVerificationCode({
    phone: form.value.phoneNumber,
    code_type: 'login',
    region: "CN"
  })

  isLoading.value = false;
}

const login = async () => {
  clearErrorMessages();

  if (form.value.phoneNumber.length !== 11) {
    usernameErrorMessage.value = '请填写正确的手机号';
    return void 0;
  }

  if (isVerificationLogin.value && form.value.verificationCode.length !== 6) {
    errorMessage.value = '请填写正确的验证码';
    return void 0;
  }

  if (!isVerificationLogin.value && form.value.password.length === 0) {
    errorMessage.value = '请填写正确的密码';
    return void 0;
  }

  const data = {
    phone: form.value.phoneNumber,
    region: "CN"
  }

  if (isVerificationLogin.value) {
    data.code = form.value.verificationCode;
  } else {
    data.password = form.value.password;
  }

  uni.showLoading({
    title: "登录中...",
    mask: true
  })

  const res = await loginApi(isVerificationLogin.value ? 'code' : 'password', data)

  uni.hideLoading()

  if (res.statusCode === 200) {
    setToken(res.data.access_token)
    uni.setStorageSync(USER_INFO_KEY, res.data.user)

    uni.showToast({
      title: "登录成功",
      icon: "success",
      duration: 3000
    })

    uni.switchTab ({ url: '/pages/Home/index' });
  } else {
    uni.showToast({
      title: "登录失败，请检查手机号和验证码/密码是否正确",
      icon:  "error",
      duration: 3000
    })
  }
}

</script>

<style lang="scss">
.login {
  --container-width: 85vw;

  .login-header {
    width: var(--container-width);
    margin: 5vh auto 15vh;

    color: #ffc300;
    font-size: 40rpx;
    font-weight: 500;
  }

  .login-main {
    width: var(--container-width);

    .nut-input {
      border: 1px solid #ffc300;
      border-radius: 8px;

      background-color: #2a2a2a;

      .nut-input__input {
        color: #fff !important;
      }
    }

    .login-username, .login-password, .login-verification {
      margin-bottom: 22px;
    }

    .login-verification {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .nut-input {
        width: 60%;
      }
    }
  }

  .login-action {
    display: flex;
    align-items: center;
    justify-content: space-between;

    width: var(--container-width);
    margin-bottom: 6vh;
  }

  .login-username__error, .login-password__error {
    height: 22px;
    margin-top: -20px;
    
    font-size: 14px;
    // line-height: 1.1;
    
    color: #ff4d4f;
  }
}
</style>